package com.xinghou.platform.dao.main.aspect;

import com.google.gson.stream.JsonToken;
import org.aspectj.lang.ProceedingJoinPoint;

import com.xinghou.platform.dao.main.common.DBShareLevelCached;
import com.xinghou.platform.model.main.SharedCard;
import com.xinghou.platform.util.JsonUtil;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SharedCardCacheAspect extends DBShareLevelCached {
	@Pointcut("execution(public * com.xinghou.platform.dao.main.SharedCardDAO.getSharedCardBycardId(..))")
	public void getSharedCardBycardId(){
	}

	@Pointcut("execution(public * com.xinghou.platform.dao.main.SharedCardDAO.updateSharedCard(..)))")
	public void updateSharedCard(){
	}

	@Pointcut("execution(public * com.xinghou.platform.dao.main.SharedCardDAO.deleteShare(..)))")
	public void deleteShare(){
	}

	@Around("deleteShare()")
	public void deleteShare(ProceedingJoinPoint pjp) throws Throwable{
		String cardid = ((Object[])pjp.getArgs())[0].toString();
		pjp.proceed();
		String id = ((Object[])pjp.getArgs())[0].toString();
		String key = String.format(CACHE_SHARE_ID , id);
		Object jsonToken = getRedisClient().get(key, CACHED_SHARE_DB_INDEX);
		if(jsonToken != null){
			SharedCard sharedCard = (SharedCard)JsonUtil.fromJson(jsonToken.toString(), SharedCard.class);
			sharedCard.setStatus(new Short("0"));
			getRedisClient().set(key, JsonUtil.toJson(sharedCard), CACHED_SHARE_DB_INDEX);


		}
	}





	@Around("getSharedCardBycardId()")
	public SharedCard getSharedCardBycardId(ProceedingJoinPoint pjp) throws Throwable{
		String id = ((Object[])pjp.getArgs())[0].toString();
		String key = String.format(CACHE_SHARE_ID , id);
		Object jsonToken = getRedisClient().get(key, CACHED_SHARE_DB_INDEX);
		if(jsonToken == null){
			SharedCard sharedCard = (SharedCard)pjp.proceed();
			if(sharedCard != null)
				getRedisClient().set(key, JsonUtil.toJson(sharedCard), CACHED_SHARE_DB_INDEX);
			return sharedCard;
		}else{
			SharedCard sharedCard = (SharedCard)JsonUtil.fromJson(jsonToken.toString(), SharedCard.class);
			return sharedCard;
		}
	}
	@Around("updateSharedCard()")
	public int updateSharedCard(ProceedingJoinPoint pjp) throws Throwable{
		
		SharedCard sharedCard = (SharedCard)((Object[])pjp.getArgs())[0];
		
		int returnno = (int) pjp.proceed();
		
		String keyInfoId = String.format(CACHE_SHARE_ID , sharedCard.getCardid().toString());
		
		if(getRedisClient().exists(keyInfoId, CACHED_SHARE_DB_INDEX)){
			getRedisClient().set(keyInfoId, JsonUtil.toJson(sharedCard), CACHED_SHARE_DB_INDEX);
		}
		
		return returnno;
	}
	
}
